package com.xms.security.api.controller;

import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.xms.core.annotation.AllowAnonymous;
import com.xms.core.org.UserContext;
import com.xms.organization.entity.Systemuser;
import com.xms.organization.service.ISystemUserService;
import com.xms.security.api.model.EditUserPasswordModel;
import com.xms.security.api.model.ResetMyPasswordModel;
import com.xms.security.entity.Privilege;
import com.xms.security.service.principal.ISystemUserPermissionService;
import com.xms.security.service.sitemap.IPrivilegeTreeBuilder;
import com.xms.utils.JsonUtil;
import com.xms.utils.MD5Util;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * UserController
 * </p>
 *
 * @author migo
 * @since 2021/9/12
 */
@RestController
@RequestMapping({"{org}/api/user", "/api/user"})
public class UserController extends ApiBaseController {
    private ISystemUserService _systemUserService;
    private IPrivilegeTreeBuilder _privilegeTreeBuilder;
    private ISystemUserPermissionService _systemUserPermissionService;

    @Autowired
    public UserController(ISystemUserService systemUserService,
                          IPrivilegeTreeBuilder privilegeTreeBuilder,
                          ISystemUserPermissionService systemUserPermissionService)
    {
        _systemUserService = systemUserService;
        _privilegeTreeBuilder = privilegeTreeBuilder;
        _systemUserPermissionService = systemUserPermissionService;
    }

    @AllowAnonymous
    @GetMapping("usercontext")
    public String getUserContext(){
        String result = "var CURRENT_USER = ";
        UserContext user = _currentUser.getUser();
        if(user != null){
            result += JsonUtil.toJSONString(user);
        }
        else{
            result += "null";
        }
        result += ";";
        return result;
    }

    @ApiOperation("获取用户权限菜单")
    @GetMapping("userprivilegestree")
    public JsonResultObject userPrivilegesTree()
    {
        if (!_currentUser.isAdministrator() && getPlatformSettings().showmenuinuserprivileges)
        {
            List<Privilege> result = _systemUserPermissionService.getPrivileges(_currentUser.getUser().SystemUserId);
            result.removeIf(n -> n.getIsvisibled() == false);
            List<HashMap<String, Object>> treeData = _privilegeTreeBuilder.build(result, UUIDUtil.Empty);
            HashMap<String, Object> contact = new HashMap<>();
            contact.put("label", "root");
            contact.put("id", UUIDUtil.Empty);
            contact.put("children", treeData);

            List<HashMap<String, Object>> results = new ArrayList<>();
            results.add(contact);

            return JOk(results);
        }
        else
        {
            String result = _privilegeTreeBuilder.build(true);
            return JOk(result);
        }
    }

    @ApiOperation("更改个人密码")
    @PostMapping("resetmypassword")
    public JsonResultObject resetMyPassword(@RequestBody ResetMyPasswordModel model)
    {
        StringBuilder errMsg = new StringBuilder();
        if (model.NewPassword.length() < 6 || model.NewPassword.length() > 16)
        {
            errMsg.append("密码长度介于6-16个字符");
        }
        if (!model.NewPassword.equalsIgnoreCase(model.ConfirmPassword))
        {
            errMsg.append("两次输入的新密码不一致");
        }
        Systemuser user = _systemUserService.getById(_currentUser.getUser().SystemUserId);
        String password = MD5Util.encode(model.OriginalPassword);
        if (!password.equalsIgnoreCase(user.getPassword()))
        {
            errMsg.append("原密码不正确");
        }
        if (errMsg.length() == 0)
        {
            String newPassword = MD5Util.encode(model.NewPassword);
            user.setPassword(newPassword);
            boolean result = _systemUserService.updateById(user);
            return result ? JUpdateSuccess() : JUpdateFailure();
        }
        return JUpdateFailure(errMsg.toString());
    }

    @ApiOperation("更改用户密码")
    @PostMapping("resetpassword")
    public JsonResultObject resetPassword(@RequestBody EditUserPasswordModel model)
    {
        StringBuilder errMsg = new StringBuilder();
        if (model.NewPassword.length() < 6 || model.NewPassword.length() > 16)
        {
            errMsg.append("密码长度介于6-16个字符");
        }
        if (!model.NewPassword.equalsIgnoreCase(model.ConfirmPassword))
        {
            errMsg.append("两次输入的新密码不一致");
        }
        if (errMsg.length() == 0)
        {
            String password = MD5Util.encode(model.NewPassword);
            Systemuser entity = _systemUserService.getById(model.SystemUserId);
            if(entity == null){
                return JNotFound();
            }
            entity.setPassword(password);
            boolean result = _systemUserService.updateById(entity);
            return result ? JUpdateSuccess() : JUpdateFailure();
        }
        return JUpdateFailure(errMsg.toString());
    }
}
